package com.cicc.springboot.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cicc.springboot.common.dto.R;
import com.cicc.springboot.entity.SrmSupplierBasicEntity;
import com.cicc.springboot.model.SupplierQuery;
import com.cicc.springboot.service.SupplierService;
import com.cicc.springboot.service.impl.SupplierExcelImportServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * Author: 张月鹿
 */


@RestController
@RequestMapping("/suppliers")
@AllArgsConstructor
public class SupplierBasicController {

    @Autowired
    private SupplierService supplierService;
    @Autowired
    private SupplierExcelImportServiceImpl<SrmSupplierBasicEntity> excelImportService;

    /**
     * 供应商信息模糊查询
     *
     * @return 调用服务层方法
     */

    @GetMapping("/search")
    public R<Page<SupplierQuery>> search(
            @RequestParam(required = false) String supplierName,
            @RequestParam(required = false) String erpCode,
            @RequestParam(required = false) String tenantState,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize) {


        return supplierService.searchSuppliers(supplierName, erpCode, tenantState, currentPage, pageSize);
    }

    /**
     * 添加供应商信息
     *
     * @param supplierQuery 前端传来的供应商信息
     * @return 返回响应结果
     */

    @PostMapping("/addSupplier")
    public R<SrmSupplierBasicEntity> addSuppliers(@RequestBody SupplierQuery supplierQuery) {
        return supplierService.addSuppliers(supplierQuery);
    }


    /**
     * 根据id删除供应商
     *
     * @param id 前端传来的id
     * @return 返回响应结果
     */
    @DeleteMapping("/deleteSupplier/{id}")
    public R<SrmSupplierBasicEntity> deleteSupplier(@PathVariable Long id) {
        return supplierService.deleteUserById(id);
    }

    /**
     * 更新供应商信息
     *
     * @param supplier 包含更新信息的 SupplierQuery 对象
     * @return 返回一个 R 对象，包含更新结果和消息
     */
    @PutMapping("/update")
    public R<SrmSupplierBasicEntity> updateSupplier(@RequestBody SupplierQuery supplier) {

        boolean isUpdated = supplierService.updateById(supplier);
        return isUpdated ? R.ok(supplier, "供应商信息更新成功") : R.failed("供应商信息更新失败");
    }

    // 重新写一遍文件上传

    /**
     * 导入供应商表 Excel 文件
     */
    @PostMapping("/import")
    public R<String> importData(@RequestParam("file") MultipartFile file) throws IOException {
        System.out.println("file = " + file.toString());
        excelImportService.importExcelData(file);
        return R.ok("Excel表数据导入成功");
    }

}
